//cType为请求的参数数据类型，定义如下：
// 1或者不写，为普通post请求；
// 2 - 表单提交形式；
// 3 - string参数式提交；


import tool from './tool'
import axios from 'axios';
import md5 from 'js-md5';
var Mint = require("mint-ui");
var _this = this;
var AccessKey = "csbr0000";
const ajaxMethod = {
  ajax: function (type, method, param) {
    Mint.Indicator.open();
    return axios({
      headers: {
        'Authorization': md5(AccessKey)
      },
      method: 'get',
      url: process.env.API_ROOT + '/api/webchart/' + method,
      params: param
    }).then((response) => {
      Mint.Indicator.close();
      return response.data;
    }).catch((error) => {
      console.log('get请求失败:', error);
      Mint.Indicator.close();
      errProcess(error);
    });
  },

  ajaxPost: function (type, method, param, cType, loadtxt) {
    var loadtxts = loadtxt || '',
      header = {
        'Authorization': md5(AccessKey)
      };
    Mint.Indicator.open(loadtxts);
    cType = cType ? cType : 1;

    //formData格式请求
    if (cType === 2) {
      header = {
        'Authorization': md5(AccessKey),
        'Content-Type': 'application/x-www-form-urlencoded'
      };
      let formdata = new FormData();
      formdata.append('dataJson', JSON.stringify(param));
      param = formdata;
    }

    //string类型请求
    return axios({
      headers: header,
      method: 'post',
      url: process.env.API_ROOT + '/api/webchart/' + method,
      data: param,
    }).then((response) => {
      Mint.Indicator.close();
      return response.data;
    }).catch((error) => {
      console.log('post请求失败:', error);
      Mint.Indicator.close();
      errProcess(error);
    });
  }
}
//输出接口请求方法
export default {
  get: function (method, param) {
    return ajaxMethod.ajax('get', method, param)
  },
  post: function (method, param, cType, loadtxt) {
    return ajaxMethod.ajaxPost('post', method, param, cType, loadtxt)
  }
}

function errProcess(error) {
  var errCode = error.response.status,
    apiName = error.response.config.url.split("/api/webchart/")[1],
    printErr = "";
  switch (errCode) {
    case 403:
      printErr = '非法接口调用，拒绝访问'
      break

    case 404:
      printErr = apiName + ' 接口不存在'
      break

    case 500:
      printErr = '内部服务器错误，请联系管理员'
      break

    case 504:
      printErr = '网络错误，请检查是否已联网'
      break

    default:
      printErr = '未知错误';
  }
  Mint.Toast(printErr);
}